#This to obtain:
#Figure_6a.jpg
rm(list = ls())
library(ggplot2)
library(dplyr)
library(lemon)
library(sf)

#Step 1: Read Data
#setwd("C:/Users/bogdanp/")
setwd("/Users/bgpopescu/")

census_1895_dist<-st_read(dsn="./Dropbox/Legacies_Project/Analysis/data/data.gdb",
        layer="census_1895_points")

#Step 2: Calculating additional variables
census_1895_dist<-st_drop_geometry(census_1895_dist)
census_1895 <- subset(census_1895_dist, inside_croatia == 1)
census_1895$dist1 <- as.numeric( with (census_1895,ifelse(census_1895$treat==1, 1, -1)))
census_1895$krajna6_distance<-census_1895$krajna6_distance/1000
census_1895$zagreb_distance<-census_1895$zagreb_distance/1000
census_1895$NAME<-census_1895$towns


data <- census_1895
data$dist1 <- as.numeric( with (data,ifelse(data$treat==1, 1, -1)))
data$dist2 <-data$dist1*data$krajna6_distance
data$bfe1 <- ifelse(data$krajna6_NEAR_FID == 1, 1,0)
data$bfe2 <- ifelse(data$krajna6_NEAR_FID == 3, 1,0)
data$bfe3 <- ifelse(data$krajna6_NEAR_FID == 4, 1,0)
data$bfe4 <- ifelse(data$krajna6_NEAR_FID == 5, 1,0)
data$bfe5 <- ifelse(data$krajna6_NEAR_FID == 6, 1,0)
data$bfe6 <- ifelse(data$krajna6_NEAR_FID == 7, 1,0)
data$bfe7 <- ifelse(data$krajna6_NEAR_FID == 8, 1,0)
data$bfe8 <- ifelse(data$krajna6_NEAR_FID == 9, 1,0)


data$area<-as.numeric(data$area)
data$log_existing_zadrugas_yokes<-log(data$existing_zadrugas_yokes+1)

#######################################
#RD GRAPH: log_existing_zadrugas_yokes#
########################3#############3

data2<-data%>%
  filter(abs(dist2)<70)%>%
  mutate(left=ifelse(dist2<0, "Civilian Teritory", "Military Teritory"))
  

log_existing_zadrugas_yokes_rd<-ggplot(data=data2, aes(dist2, log_existing_zadrugas_yokes, color=left, label=NAME))+
  geom_smooth(method="lm")+
  geom_point(size=0.5)+
  scale_x_continuous(name="Bandwidth (km)", breaks = seq(-70, 70, 20)) +
  scale_y_continuous(name="Log Existing Zadrugas in Yokes 1895")+
  geom_vline(xintercept = 0)+
  theme(plot.title = element_text(hjust = 0.5))+
  ggtitle("")+
  geom_text(aes(label = NAME),
            size = 2, check_overlap = TRUE, position = position_nudge(y = 0.3))+
  theme_bw()+
  scale_color_manual("", values=c("Civilian Teritory"="black", "Military Teritory"="red"), guide='legend')+
  theme(plot.title = element_text(hjust = 0, size=15),
        axis.text=element_text(size=12),
        axis.title.x = element_text(size=15),
        axis.title.y = element_text(size=15),)+
  theme(legend.position=c(0.85,0.85),
        legend.box.background = element_rect(fill='white'),
        legend.background = element_blank(),
        legend.text=element_text(size=10))

log_existing_zadrugas_yokes_rd<-reposition_legend(log_existing_zadrugas_yokes_rd, 'bottom right')

ggsave(log_existing_zadrugas_yokes_rd, 
       file="./Dropbox/Legacies_Project/Paper/figures/Figure_6a.jpg", 
       height=10, width=20, 
       units = "cm", dpi=300)

